package com.leyou.controller;

import com.leyou.ResponseData;
import com.leyou.service.FileUploadService;
import com.leyou.utils.UuidUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    @RequestMapping("/upload")
    public ResponseData fileUpload(MultipartFile multipartFile) {
        try {
            if (multipartFile == null || multipartFile.isEmpty()) {
                return ResponseData.error(400, "文件不能为空!", null);
            }
            String newFileName = UuidUtils.genFileName(multipartFile.getOriginalFilename());
            byte[] data = multipartFile.getBytes();
            String fileUrl = fileUploadService.uploadFile(newFileName, data);
            if (StringUtils.isNotBlank(fileUrl)) {
                return ResponseData.ok(fileUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.error(401, "文件上传失败!", null);
    }
}